<?php
/*配送模块*/
namespace YMApi\Controller;
use Think\Controller;
use Common\Api\Ali_ossApi;

class DistributionController extends AppController {
	public $pagesize=10;

	public function _initialize($apptoken = '', $apptime = '', $check_uid = false, $session_id = '',$check_sign=true)
	{
		parent::_initialize($apptoken, $apptime, $check_uid, $session_id,false);
	}
	
	/*登录*/
	//TODO 用户登录
	public function login(){
		$name=I('post.name');
		if(empty($name)){
			returnApiError('用户名不能为空');
		}
		$password=I('post.password');
		if(empty($password)){
			returnApiError('密码不能为空');
		}
		$admin_user=M('admin_user');
		$ec_salt=$admin_user->field('ec_salt')->where(array('user_name'=>$name))->find();
		if(!empty($ec_salt['ec_salt'])){
			$password=md5(md5($password).$ec_salt['ec_salt']);
		}else{
			$password=md5($password);
		}
	
		$row=$admin_user->field('user_id,user_name,email,add_time')->where(array('user_name'=>$name,'password'=>$password))->find();
		//dump($admin_user->getlastsql());
		if($row){
			$warehouse_personnel=M('warehouse_personnel');
			$wprow=$warehouse_personnel->field('position,wid,longitude,latitude,status')->where(array('uid'=>$row['user_id'],'status'=>1))->find();

			//dump($wprow);
			if($wprow){


				$phone = I('post.phone');
				$nickname = I('post.nickname');
				w_log("ss",$phone.":".$nickname);
				if(!empty($phone)){
					$phone = trim($phone);
					$data['phone'] = $phone;
				}
				if(!empty($nickname)){
					$data['name'] = $nickname;
				}
				if(!empty($phone)||!empty($name)){
					M('warehouse_personnel')->where(array('uid'=>$row['user_id']))->save($data);
				}



				$user_phone = $warehouse_personnel->field('phone,name')->where(array('uid'=>$row['user_id']))->find();
				$row['position']=$wprow['position'];
				$row['wid']=$wprow['wid'];
				$row['longitude']=$wprow['longitude'];
				$row['latitude']=$wprow['latitude'];
				$row['status']=$wprow['status'];
				$row['phone']=$user_phone['phone'];
				$row['name']=$user_phone['name'];
				$users=array('user'=>$row);
				$ip=get_client_ip();
				//记录登录日志
				$id=$admin_user->where(array('user_id'=>$row['user_id']))->save(array('last_login'=>gmtime(),'last_ip'=>$ip));
				if($id!=false){
				    //dump($wprow['position']);
				    //exit();
					switch ($wprow['position']){
						case 1:
							$log_info = "配货员-APP登录".$user_phone['name']."[".$name."]";
						break;
						case 2:
							$log_info = "配送员-APP登录".$user_phone['name']."[".$name."]";
						break;
						case 3:
							$log_info = "仓管员-APP登录".$user_phone['name']."[".$name."]";
						break;
                        default:
                            returnApiError("无权限登录");
                            break;

					}
					$data=array(
							'log_time'=>gmtime(),
							'user_id'=>$row['user_id'],
							'log_info'=>$log_info,
							'ip_address'=>$ip
					);
					M('admin_log')->add($data);
				}
				returnApiSuccess($users,'登录成功');
			}else{
				returnApiError('该用户没有权限登录');
			}
		}else{
			returnApiError('登录失败');
		}
	}


	/**
	 * TODO 修改用户的手机号和用户名
     */
	public function update_name_phone(){

		$user_id = I('post.user_id');
		$phone = I('post.phone');
		$name = I('post.name');

		if(empty($user_id)){
			returnApiError("USER ID 不存在");
		}
		if(empty($phone)||empty($name)){
			returnApiError("手机号/姓名为空");
		}
		$phone = trim($phone);
		$data['phone'] = $phone;
		$data['name'] = $name;
		M('warehouse_personnel')->where(array('uid'=>$user_id))->save($data);
		returnApiSuccess(null,"修改成功");

	}


	/**
	 * 获取配送区域（关联待配送列表）
     */
	public function get_area(){
		$user_id=I('post.user_id','intval');
		if(!isset($user_id)){
			returnApiError('参数错误');
		}
		$wp=$this->check_warehouse_personnel($user_id);
		if(!$wp){
			returnApiError('非法用户或者该用户已被禁用');
		}
		$where['wp_userid']=$user_id;
		$where['pay_status']=array("EGT",2);
		$where['order_status']=1;
		$where['shipping_status']=5;
		$wdr_list = M('order_info')->where($where)->getField("wdr_id",true);	//查询所有的配送区域ID
		$wdr_list = array_unique($wdr_list);
		if(count($wdr_list)>0){
			$where_wdr['id']=array("IN",implode(",",$wdr_list));
			$wdr_str = M("warehouse_deliver_region")->where($where_wdr)->field("id,name")->select();
			$all=array(
				"id" => 0,
				"name" => "全部"
			);
			$re_wdr = array_merge($all,$wdr_str);
			returnApiSuccess($re_wdr,"已返回数据");
		}else{
			returnApiError("无订单");
		}
	}




	/*TODO 待配送列表*/
    public function prepare_list(){
        $user_id=I('post.user_id','intval');

        if(!isset($user_id)){
        	returnApiError('参数错误');
        }
        $wp=$this->check_warehouse_personnel($user_id);
        if(!$wp){
        	returnApiError('非法用户或者该用户已被禁用');
        }

		$id=I('post.id');	//配货区域ID
		if(!empty($id)){
			$where['wdr_id']=$id;
		}

        $page=I('post.page','intval');
        $where['wp_userid']=$user_id;
        $where['pay_status']=array("EGT",2);
        $where['order_status']=1;
        $where['shipping_status']=5;
        $count=M('order_info')->where($where)->count();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
        	$is_last=1;
        }else{
        	$is_last=0;
        }
        $list=M('order_info')->field('order_id,wid,wdr_id,postscript,best_time_start,best_time,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')->where($where)->limit($pagearr['firstpage'].','.$this->pagesize)->order('add_time desc,order_id desc')->select();
        if($list){
        	$order_goods=M('order_goods');
        	foreach ($list as $k=>$v){
        		$country_name=$this->get_region_name($v['country']);
        		$province_name=$this->get_region_name($v['province']);
        		$city_name=$this->get_region_name($v['city']);
        		$district_name=$this->get_region_name($v['district']);
        		$list[$k]['address']=$country_name.$province_name.$city_name.$district_name.$v['address'].$v['sign_building'].$v['address_name'];
        		$list[$k]['order_time']=date('Y-m-d H:i:s',$v['order_time']+(8*3600));
        		$list[$k]['order_state']=0;
				$list[$k]['order_remark']=$v['postscript']; //订单备注
				$list[$k]['order_want_time']=date('Y-m-d H:i:s',$v['best_time_start'])."\n".date('Y-m-d H:i:s',$v['best_time']); //预期送达时间
				$list[$k]['order_area']=M("warehouse_deliver_region")->where(array("id"=>$v['wdr_id']))->getField('name'); //配货区域
				$list[$k]['order_store']=M("warehouse")->where(array("id"=>$v['wid']))->getField('name'); //配货区域
				$result['weight']=$this->get_order_weight($v['order_id']); //订单重量



				$goods_list = A('Sorting')->sh_goods_list($v['order_id'],$v['wid']);
				if($goods_list){
					$list[$k]['goods_list']=$goods_list;
				}else{
					unset($list[$k]);
				}


				$re_goods_list = A('Sorting')->re_goods_list($v['order_id'],$v['wid']);
				if($re_goods_list){
					$list[$k]['goods_list_back']=$re_goods_list;
				}
        	}
        	returnApiSuccess(array('list'=>$list,'is_last'=>$is_last),'success');
        }else{
        	returnApiError('没有数据');
        }
        
    }
    
    /*TODO 配送中列表*/
    public function distribute_list(){
        $user_id=I('post.user_id','intval');
        if(!isset($user_id)){
        	returnApiError('参数错误');
        }
        $wp=$this->check_warehouse_personnel($user_id);
        if(!$wp){
        	returnApiError('非法用户或者该用户已被禁用');
        }



        //获取群组中的配送订单
        $map = array('g.status'=>1,'g.user_id'=>$user_id);
        $deliver_order_group = D('warehouse_deliver_order_group');
        $group_orders = $deliver_order_group->alias('go')->join('left join '.C('DB_PREFIX').'warehouse_deliver_group g on g.group_id = go.group_id')->field('go.order_id as order_id')->where($map)->select();
        $order_ids = array();
        foreach ($group_orders as $order){
        	$order_ids[] = $order['order_id'];
        }



		$id=I('post.id');	//配货区域ID
		if(!empty($id)){
			$where['wdr_id']=$id;
		}
        $page=I('post.page','intval');
        $where['wp_userid']=$user_id;
        $where['pay_status']=array("IN","2,3");
        $where['order_status']=5;
        $where['shipping_status']=1;
        //$where['_string']='order_status=5 and shipping_status=1';
        
        if(count($order_ids)>0){
        	$where['order_id'] = array('not in',$order_ids);
        }
        
        $count=M('order_info')->where($where)->count();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
        	$is_last=1;
        }else{
        	$is_last=0;
        }
        $list=M('order_info')->field('longitude,latitude,sorting_id,wp_userid,order_id,wid,wdr_id,postscript,best_time_start,best_time,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')->where($where)->limit($pagearr['firstpage'].','.$this->pagesize)->order('shipping_time desc,order_id desc')->select();
        $dcount=M('order_info')->where($where)->count();
        if($list){
           foreach ($list as $k=>$v){
			   $country_name=$this->get_region_name($v['country']);
			   $province_name=$this->get_region_name($v['province']);
			   $city_name=$this->get_region_name($v['city']);
			   $district_name=$this->get_region_name($v['district']);


			   $deploy_info = $this->get_admin_user_name($v['sorting_id']);
			   $distribute_info = $this->get_admin_user_name($v['wp_userid']);
			   $list[$k]['deploy_name'] = $deploy_info['user_name']; //配货员姓名
			   $list[$k]['deploy_phone'] = $deploy_info['phone']; //配货员手机号码
			   $list[$k]['distribute_name'] = $distribute_info['user_name']; //配送员姓名
			   $list[$k]['distribute_phone'] = $distribute_info['phone']; //配送员手机号码

			   $list[$k]['longitude'] = $v['longitude']; //经度
			   $list[$k]['latitude'] = $v['latitude']; //纬度


			   $list[$k]['address']=$country_name.$province_name.$city_name.$district_name.$v['address'].$v['sign_building'].$v['address_name'];
			   $list[$k]['order_time']=date('Y-m-d H:i:s',$v['order_time']+(8*3600));
			   $list[$k]['order_state']=1;

			   $list[$k]['order_remark']=$v['postscript']; //订单备注
			   $list[$k]['order_want_time']=date('Y-m-d H:i:s',$v['best_time_start'])."\n".date('Y-m-d H:i:s',$v['best_time']); //预期送达时间
			   $list[$k]['order_area']=M("warehouse_deliver_region")->where(array("id"=>$v['wdr_id']))->getField('name'); //配货区域
			   $list[$k]['order_store']=M("warehouse")->where(array("id"=>$v['wid']))->getField('name'); //配货区域

			   $goods_list = A('Sorting')->sh_goods_list($v['order_id'],$v['wid']);
			   if($goods_list){
				   $list[$k]['goods_list']=$goods_list;
			   }else{
				   unset($list[$k]);
			   }

			   $re_goods_list = A('Sorting')->re_goods_list($v['order_id'],$v['wid']);
			   if($re_goods_list){
				   $list[$k]['goods_list_back']=$re_goods_list;
			   }
        	}
        	returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count_prepare'=>$dcount),'success');
        }else{
        	returnApiError('没有数据',array('count_prepare'=>$dcount));
        }
    }
    
    /*
     * TODO 配送完列表
     * */
    public function distributed_list(){
    	$user_id=I('post.user_id','intval');
    	
        if(!isset($user_id)){
        	returnApiError('参数错误');
        }
        $wp=$this->check_warehouse_personnel($user_id);
        if(!$wp){
        	returnApiError('非法用户或者该用户已被禁用');
        }
        $page=I('post.page','intval');
        $year = I('post.year','intval');
        $month = I('post.month','intval');
        if($year>0 && $month>0){
        	$days = date('t', strtotime($year."-".$month));
        	$begintime = strtotime($year."-".$month."-1");
        	$endtime = strtotime($year."-".$month."-".$days." 23:59:59");
        	
        	$where['confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
        }
        
        
        $where['wp_userid']=$user_id;
//        $where['pay_status']=array("in","2,3");
//        $where['order_status']=5;
        $where['shipping_status']=2;
        $count=M('order_info')->where($where)->count();
//         $sql = M('order_info')->getLastSql();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
        	$is_last=1;
        }else{
        	$is_last=0;
        }
        $list=M('order_info')->field('outgo,order_id,wid,wdr_id,postscript,best_time_start,best_time,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
            ->where($where)->limit($pagearr['firstpage'].','.$this->pagesize)->order('confirm_time desc,order_id desc')->select();
        $v=$GLOBALS;
        if($list){
        	$order_goods=M('order_goods');
        	$arr='';
           foreach ($list as $k=>$v){
        		$country_name=$this->get_region_name($v['country']);
        		$province_name=$this->get_region_name($v['province']);
        		$city_name=$this->get_region_name($v['city']);
        		$district_name=$this->get_region_name($v['district']);
        		$list[$k]['address']=$country_name.$province_name.$city_name.$district_name.$v['address'].$v['sign_building'].$v['address_name'];
        		$list[$k]['order_time']=date('Y-m-d H:i:s',$v['order_time']+(8*3600));

//        		if($v['order_state'] = 2){
//                    $list[$k]['order_state']=3;
//                }else{
                    $list[$k]['order_state']=2;
                //}
        		$list[$k]['outgo']=$v['outgo'];
			   $list[$k]['order_remark']=$v['postscript']; //订单备注
			   $list[$k]['order_want_time']=date('Y-m-d H:i:s',$v['best_time_start'])."\n".date('Y-m-d H:i:s',$v['best_time']); //预期送达时间
			   $list[$k]['order_area']=M("warehouse_deliver_region")->where(array("id"=>$v['wdr_id']))->getField('name'); //配货区域
			   $list[$k]['order_store']=M("warehouse")->where(array("id"=>$v['wid']))->getField('name'); //配货区域

			   $goods_list = A('Sorting')->sh_goods_list($v['order_id'],$v['wid']);
			   if($goods_list){
				   $list[$k]['goods_list']=$goods_list;
			   }else{
				   unset($list[$k]);
			   }
			   $re_goods_list = A('Sorting')->re_goods_list($v['order_id'],$v['wid']);
			   if($re_goods_list){
				   $list[$k]['goods_list_back']=$re_goods_list;
			   }
        	}
        	returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }else{
        	$list = array();
        	$is_last =1;
        	$count = 0;
        	returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }
    }
    
    /*TODO 开始配送*/
    public function distribute(){
        $user_id=I('post.user_id','intval');
        $order_id=I('post.order_id','intval');
        if(!isset($user_id) || !isset($order_id)){
        	returnApiError('参数错误');
        }
        $wp=$this->check_warehouse_personnel($user_id);
        if(!$wp){
        	returnApiError('非法用户或者该用户已被禁用');
        }
        //$where['user_id']=$user_id;
        $where['order_id']=$order_id;
		$where['pay_status']=array("in","2,3");
		$where['order_status']=array("neq","2");
        $list=M('order_info')->field('order_id,order_sn,user_id,order_status,shipping_status,pay_status,mobile,consignee,best_time,best_time_start,pay_time,is_presell,wid')->where($where)->find();
        if($list['order_id']){
                try {
                    $data['order_status']=5;
                    $data['shipping_status']=1;
                    $data['shipping_time']=gmtime();
                    $data['wp_userid'] = $user_id;
                    $id=M('order_info')->where($where)->save($data);
                    if($id!=false){
                       /* $ordergoods=D('Orderinfo')->get_ordergoods($list['order_id'],1);//搜预售订单商品，有就减相应的实际库存，并且记录
                        if($ordergoods){
                            foreach ($ordergoods as $k=>$v){
                                //减去实际库存
                                D('Goodsstorage')->save_theactual_goods($list['wid'],$v['goods_id'],$v['goods_number']);
                                $goodsstorage=D('Goodsstorage')->get_warehous_goods($list['wid'],$v['goods_id']);
                                $goodsrecord=array(
                                    'goods_storage_id'=>$goodsstorage['id'],
                                    'wpid'=>0,
                                    'wid'=>$goodsstorage['wid'],
                                    'goods_id'=>$v['goods_id'],
                                    'goods_sn'=>$v['goods_sn'],
                                    'operation_num'=>$v['goods_number'],
                                    'operation_userid'=>$user_id,
                                    'operation_addtime'=>gmtime(),
                                    'record_type'=>4,
                                    'remark'=>'配送出库',
                                );
                                //商品出入库记录
                                D('Goodsstoragerecord')->add_storage_record($goodsrecord);
                                $goodsfreezerecord=array(
                                    'goods_storage_id'=>$goodsstorage['id'],
                                    'wid'=>$goodsstorage['wid'],
                                    'goods_id'=>$v['goods_id'],
                                    'goods_sn'=>$v['goods_sn'],
                                    'goods_name'=>$v['goods_name'],
                                    'freeze_num'=>$v['goods_number'],
                                    'operation_userid'=>$user_id,
                                    'operation_addtime'=>gmtime(),
                                    'record_type'=>4,
                                    'remark'=>'商品下单',
                                );
                                //商品冻结出入记录
                                D('Goodsfreezerecord')->add_freeze_record($goodsfreezerecord);
                            }
                        }*/
                        
                        /*$wdodata['order_status']=1;
                         $wdoid=M('warehouse_deliver_order_mod')->where($where)->save($wdodata);
                         if($wdoid!=false){*/
                        $a=array(
                            'order_id'=>$list['order_id'],
                            'user_id'=>$user_id,
                            'order_status'=>5,
                            'shipping_status'=>1,
                            'pay_status'=>$list['pay_status'],
                            'action_note'=>'已发货'
                        );
                        
                        $this->record_diliveryman_log($a);//记录配送员操作日志
                        // 	        		    $send=array(
                        // 	        		        'messcode'=>'order_distribution',//订单开始配送
                        // 	        		        'mobile'=>$list['mobile'],
                        // 	        		        'consignee'=>$list['consignee'],
                        // 	        		        'user_rank'=>'',
                        // 	        		        'order_sn'=>$list['order_sn'],
                        // 	        		        'ver_code'=>'',
                        // 	        		        'user_id'=>$list['user_id']
                        // 	        		    );
                        // 	        		    sdx_sendsms($send);  //发送订单配送短信给收货人
                        $remark['phone'] = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('phone');
                        
                        if($list['best_time_start']==0){
                        	if($list['is_presell']==1){
                        		$new_best_time = date("Y-m-d",$list['best_time'])." 20:30:00";
                        		$list['best_time'] = strtotime($new_best_time)-1;
                        		$list['best_time_start'] = strtotime(date("Y-m-d",$list['best_time'])." 10:00:00");
                        	}else{
                        		$list['best_time_start'] = $list['best_time']-2*3600;
                        	}
                        }
                        $datetime = date("Y-m-d",$list['best_time_start']);
                        
                        $remark['best_time'] = $datetime.' '.date("H:i:s",$list['best_time_start']).'-'.date("H:i:s",$list['best_time']);
                        
                        $send_result = A("Smsapi")->send_message_api('shipping_start_notice',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],$remark);
                        returnApiSuccess(array('id'=>$id),'配送订单成功');
                        /*}else{
                         returnApiError('配送订单失败');
                        }*/
                    }else{
                        returnApiError('配送订单失败');
                    }
                }catch(Exception $e){
                    returnApiErrorExample($e->getMessage());
                } 	
        }else{
        	returnApiError('查无此订单/订单状态不正常');
        }
        
    }
    
    /*TODO 配送结束*/
    public function distributed(){
       $user_id=I('post.user_id','intval');
        $order_id=I('post.order_id','intval');
        if(!isset($user_id) || !isset($order_id)){
        	returnApiError('参数错误');
        }
        $wp=$this->check_warehouse_personnel($user_id);
        if(!$wp){
        	returnApiError('非法用户或者该用户已被禁用');
        }
        //$where['user_id']=$user_id;
        $where['order_id']=$order_id;
		$where['pay_status']=array("in","2,3");
		$where['order_status']=array("neq","2");

        $list=M('order_info')->field('order_id,order_sn,wid,user_id,order_status,shipping_status,pay_status,mobile,consignee')->where($where)->find();
        if($list['order_id']){
        	if($list['order_status']==5 && $list['shipping_status']==2){
        		returnApiError('此单已确认收货，不用重复确认');
        	}
        	try {
                if($_FILES['photo']['size']>100){
                    $path= "uploads/refund_pic/".rand(10000000,99999999).".".end(explode('.', $_FILES['photo']['name']));
                    Ali_ossApi::upload($path, $_FILES['photo']['tmp_name']);
                }


	        	$data['order_status']=5;
	        	$data['shipping_status']=2;
	        	$data['done_photo']=$path;
	        	$data['confirm_time']=gmtime();
	        	$data['wp_userid']=$user_id;
	        	$id=M('order_info')->where($where)->save($data);
		        	if($id!=false){
		        	    /*$wdodata['order_status']=2;
		        		$wdoid=M('warehouse_deliver_order_mod')->where($where)->save($wdodata);
		        		if($wdoid!=false){*/
		        		  $this->order_buckle_inventory($list);   
		        	      $a=array(
		        		       'order_id'=>$list['order_id'],
		        		       'user_id'=>$user_id,
		        		       'order_status'=>5,
		        		       'shipping_status'=>2,
		        		       'pay_status'=>$list['pay_status'],
		        		       'action_note'=>'配送完成,收货确认'
		        		   );
		        		    $this->record_diliveryman_log($a);//记录配送员操作日志
// 		        		  $send=array(
// 		        		        'messcode'=>'order_finish',//订单完成
// 		        		        'mobile'=>$list['mobile'],
// 		        		        'consignee'=>$list['consignee'],
// 		        		        'user_rank'=>'',
// 		        		        'order_sn'=>$list['order_sn'],
// 		        		        'ver_code'=>'',
// 		        		        'user_id'=>$list['user_id']
// 		        		    );
// 		        		    sdx_sendsms($send);  //发送订单配送完成短信给收货人
		        		    
		        		    //发送订单配送完成短信给收货人
		        		    $send_result = A("Smsapi")->send_message_api('order_finish',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id']);
		        		    $this->insert_ready_sendmsg_order($list);
		        			returnApiSuccess(array('id'=>$id),'收货确认');
		        		/*}else{
		        			returnApiError('收货失败');
		        		}*/
		        	}else{
		        		returnApiError('收货失败');
		        	}
	        	}catch (Exception $e){
	        		returnApiErrorExample($e->getMessage());
	        	}
        	
        }else{
        	returnApiError('查无此订单/订单状态不正常');
        }
    }
    
    /**
     * 保存准备发送短信的已确认订单
     */
    public function insert_ready_sendmsg_order($order){
	    $data=array();
	    $data['order_id']=$order['order_id'];
	    $data['order_sn']=$order['order_sn'];
	    $data['consignee']=$order['consignee'];
	    $data['uid']=$order['user_id'];
	    $data['mobile_phone']=$order['mobile'];
	    $data['send_time']=gmtime()+7200;
	    $data['is_send']=0;
	    M("order_confirm_sendmsg")->data($data)->add();
	}
    
    /*
     * TODO 收货确认减冻结库存
     * */
    private  function order_buckle_inventory($order){
        $wid=$order['wid'];
        $where='(order_id='.$order['order_id'].' and is_presell=0) or (order_id='.$order['order_id'].' and is_presell=1 and buckle_inventory=1)';
        $order_goods=M('order_goods')->where($where)->select();
        if($order_goods){
            $goodsstorage_mod=D('Goodsstorage');
            $goodsfreezerecord=D('Goodsfreezerecord');
            $refund_detail=M('refund_detail');
            $rdgoods=array();
            //检查退货退款时是否已经减掉了冻结库存，若有，该操作则不进行减操作
            $rdlist=$refund_detail->field('goods_id,SUM(refund_number) as refund_number')
                                  ->where(array('order_id'=>$order['order_id']))
                                  ->group('goods_id')
                                  ->select();
            if($rdlist){
                foreach ($rdlist as $key=>$val){
                    $rdgoods[$val['goods_id']]=$val['refund_number'];
                }
            }
            foreach ($order_goods as $k=>$v){
                $gsdata=$goodsstorage_mod->get_warehous_goods($wid,$v['goods_id']);
                if($gsdata){
                    if(!empty($rdgoods[$v['goods_id']])){
                        $refund_number=$rdgoods[$v['goods_id']];
                        $v['goods_number']=$v['goods_number']-ceil($refund_number);
                    }
                    //减去冻结库存
                    $goodsstorage_mod->save_freeze_theactual_goods($wid,$v['goods_id'],$v['goods_number']);
                    $goodsfreezerecorddata=array(
                        'goods_storage_id'=>$gsdata['id'],
                        'wid'=>$wid,
                        'goods_id'=>$v['goods_id'],
                        'goods_sn'=>$v['goods_sn'],
                        'goods_name'=>$v['goods_name'],
                        'freeze_num'=>$v['goods_number'],
                        'real_num'=>0,
                        'frozen_num'=>$gsdata['freeze_num']-$v['goods_number'],
                        'defective_num'=>0,
                        'operation_userid'=>0,
                        'average_userid'=>$order['user_id'],
                        'operation_addtime'=>gmtime(),
                        'source_no'=>$order['order_sn'],
                        'record_type'=>6,
                        'remark'=>'确认收货',
                    );
                    //生成冻结库存记录
                    $goodsfreezerecord->add_freeze_record($goodsfreezerecorddata);
                }else{
                    continue;
                }
            }
        }else{
            return false;
        }
    }
    
     /* TODO 扫码条码*/
    public function scanner(){
        $wp_userid=I('post.user_id','intval');
        $order_id=I('post.barcode');
		$order_number=I('post.order_number');   //手动输入的订单号后8位


		if(empty($order_id)){
			if(!isset($wp_userid) || !isset($order_number)){
				if(!is_numeric($order_number)){
					returnApiError('参数错误');
				}
			}
		}else{
			if(!isset($wp_userid) || !isset($order_id)){
				returnApiError('参数错误');
			}
		}
        $wp=$this->check_warehouse_personnel($wp_userid);
        if(!$wp){
        	returnApiError('非法用户或者该用户已被禁用');
        }
        //$where['wp_userid']=$wp_userid;

		if(empty($order_id)){
			$where['order_sn']=array("like","%".$order_number);
		}else{
			$where['order_id']=$order_id;
		}

        $where['pay_status']=array('EGT',2);
		$where['order_status']=array('neq',2);
		$where['shipping_id']=3;
		$where['outgo']=1;	    //商品已经出仓
		$where['shipping_status']=5;	    //配货已经完成

        $order=M('order_info')->field('wid,wdr_id,postscript,best_time_start,best_time,order_id,order_sn as order_num,order_status as order_state,shipping_status,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,wp_userid')->where($where)->find();

		//dump(M('order_info')->getlastsql());

		if($order){
        	try {
	        	if($order['wp_userid']==0 || $order['wp_userid']==$wp_userid){
		        	    $country_name=$this->get_region_name($order['country']);
		        		$province_name=$this->get_region_name($order['province']);
		        		$city_name=$this->get_region_name($order['city']);
		        		$district_name=$this->get_region_name($order['district']);
		        		$data['order_id']=$order['order_id'];
		        		$data['order_num']=$order['order_num'];
		        		$data['address']=$country_name.$province_name.$city_name.$district_name.$order['address'];
		        		$data['order_time']=date('Y-m-d H:i:s',$order['order_time']+(8*3600));
						$data['order_remark']=$data['postscript']; //订单备注
						$data['order_want_time']=date('Y-m-d H:i:s',$order['best_time_start'])."\n".date('Y-m-d H:i:s',$order['best_time']); //预期送达时间
					$data['order_area']=M("warehouse_deliver_region")->where(array("id"=>$data['wdr_id']))->getField('name'); //配货区域
					$data['order_store']=M("warehouse")->where(array("id"=>$data['wid']))->getField('name'); //配货区域
					if($order['order_state'] !=2 && $order['shipping_status']==5){
		        			$data['order_state']=0; //待配送
		        		}elseif ($order['order_state']!=2 && $order['shipping_status']==1){
		        			$data['order_state']=1;  //配送中
		        		}elseif($order['order_state']!=2 && $order['shipping_status']==2){
		        			$data['order_state']=2;  //收货确认
		        		}else{
		        			returnApiError('订单不在待配送/配送中/已收货状态');
		        		}
// 		        		$orid=M('order_info')->where(array('order_id'=>$order_id))->save(array('wp_userid'=>$wp_userid));
		        		$data['phone']=$order['phone'];
		        		$data['name']=$order['name'];
		        		$order_goods=M('order_goods');
		        		$goods=$order_goods->field('goods_sn as goods_number,goods_id as id,goods_name as name,goods_price as price,goods_number as `count`')->where(array('order_id'=>$order['order_id']))->select();
		        		$data['goods_list']=$goods;

					$goods_list = A('Sorting')->sh_goods_list($order['order_id'],$order['wid']);
					if($goods_list){
						$data['goods_list']=$goods_list;
					}

					$re_goods_list = A('Sorting')->re_goods_list($order['order_id'],$order['wid']);
					if($re_goods_list){
						$data['goods_list_back']=$re_goods_list;
					}

		        		//M('order_info')->where($where)->save(array('shipping_status'=>1));//修改配送状态为发货中
		        		returnApiSuccess(array('distribute'=>$data));
	        	    }else{
	        	    	returnApiError('此订单已有配送员认领');
	        	    }
        	}catch (Exception $e){
        		returnApiErrorExample($e->getMessage());
        	}
        }else{
        	returnApiError('查无此条码');
        }
    }
    
    /*
     * TODO 配送员定位收集
     * */
    
    public function position(){
        $user_id=I('post.user_id','intval');
        $longitude=I('post.longitude');
        $latitude=I('post.latitude');
        if(!isset($user_id) || !isset($longitude) || !isset($latitude)){
        	returnApiError('参数错误');
        }
        $where['uid']=$user_id;
        $where['status']=1;
        $warehouse_personnel=M('warehouse_personnel');
        $list=$warehouse_personnel->field('id,uid,wid')->where($where)->find();
        if($list){
        	$data['longitude']=$longitude;
        	$data['latitude']=$latitude;
        	$id=$warehouse_personnel->where($where)->save($data);
            if($id!=false){
                $wdldata['wp_uid']=$user_id;
                $wdldata['longitude']=$longitude;
                $wdldata['latitude']=$latitude;
                $wdldata['add_time']=gmtime();
                $welid=M('warehouse_diliveryman_log')->add($wdldata);
            	if($welid){
                  returnApiSuccess(array('id'=>$welid),'定位收集成功');
            	}else{
            	    returnApiError('定位收集记录失败');
            	}
            }else{
            	returnApiError('定位收集失败');
            }
        }else{
        	returnApiError('查无此人或者账号被禁用');
        }
        
    }
    
    /*TODO 插入到配送订单列表中*/
    public function deliver_order(){
    	//$user_id=I('post.user_id','intval');
        $order_id=I('post.order_id','intval');
        $adminid=I('post.adminid','intval');
        if(!isset($order_id) || !isset($adminid)){  
        	returnApiError('参数错误');
        }
        //$where['user_id']=$user_id;
        $where['order_id']=$order_id;
        
        $where['pay_status']=array('EGT',2);
        $order=M('order_info')->field('order_id,order_sn,user_id,consignee,country,province,city,district,address,mobile,add_time,pay_time,order_status,shipping_status,pay_status,is_presell')->where($where)->find();
        
        if($order){
        	$data=array(
    		     'order_id'=>$order['order_id'],
    		     'order_sn'=>$order['order_sn'],
    		     'user_id'=>$order['user_id'],
    		     'order_consignee_name'=>$order['consignee'],
    		     'country'=>$order['country'],
    		     'province'=>$order['province'],
    		     'city'=>$order['city'],
    		     'district'=>$order['district'],
    		     'order_consignee_addr'=>$order['address'],
    		     'order_consignee_phone'=>$order['mobile'],
    		     'add_time'=>gmtime(),
    		     'order_paytime'=>$order['pay_time'],
    		     'order_status'=>0
    		);
        	$order_goods=M('order_goods')->field('rec_id,order_id,goods_id')->where(array('order_id'=>$order['order_id']))->select();
        	
//         	$good_ids='';
			$good_ids=array();
        	if($order_goods){
//         		foreach ($order_goods as $k=>$v){
//         			$good_ids.=$v['goods_id'].',';
//         		}
//         		if($good_ids){
//         			$good_ids=substr($good_ids,0,strlen($good_ids)-1);
//         		}
        		foreach ($order_goods as $k=>$v){
        			$good_ids[]=$v['goods_id'];
        		}
        		$good_ids = implode(',', $good_ids);
        		$data['order_goods']=$good_ids;
        		$id=M('warehouse_deliver_order')->add($data);
        		if($id){
        			/*按配送区域自动分派仓库*/
        			//$this->auto_updateorder_warehouse($user_id, $order_id);
        			M('order_info')->where($where)->save(array('shipping_status'=>3));//修改配送状态为配货中
        			$a=array(
        		       'order_id'=>$order['order_id'],
        		       'user_id'=>$adminid,
        		       'order_status'=>1,
        		       'shipping_status'=>3,
        		       'pay_status'=>$order['pay_status'],
        		       'action_note'=>'配货中'
        		   );
        		    $this->record_diliveryman_log($a);//记录配送员操作日志
        			returnApiSuccess(array('id'=>$id),'配货订单成功');
        		}else{
        			returnApiError('配货订单失败');
        		}
        	}else{
        		returnApiError('空订单，没有任何商品');
        	}
        	
        }else{
        	w_log('deliver_order_test',"'查无此订单");
        	returnApiError('查无此订单');
        }
    }
    
    /*
     * TODO 按配送区域自动分派仓库
     * */
    public   function auto_updateorder_warehouse(){
        $user_id=I('post.user_id','intval');
        $order_id=I('post.order_id','intval');
        /*$user_id=$_REQUEST['user_id'];
        $order_id=$_REQUEST['order_id'];*/
        if(!isset($user_id) || !isset($order_id)){
            returnApiError('参数错误');
        }
        $where['user_id']=$user_id;
        $where['order_id']=$order_id;
        //$where['pay_status']=2;
        $order_info=M('order_info');
        $list=$order_info->field('order_id,order_sn,user_id,country,province,city,district,address')->where($where)->find();
        if($list){
            $country_name=$this->get_region_name($list['country']);
            $province_name=$this->get_region_name($list['province']);
            $city_name=$this->get_region_name($list['city']);
            $district_name=$this->get_region_name($list['district']);
            $address=$country_name.$province_name.$city_name.$district_name.str_replace(' ','',$list['address']);
            $lnglat=get_lng_lat($address,$city_name);
            if(!empty($lnglat['lng']) || !empty($lnglat['lat'])){
                $longitude=$lnglat['lat'];
                $latitude=$lnglat['lng'];
                $wdr_mod=M('warehouse_deliver_region');
                $wdrc_mod=M('warehouse_deliver_region_coordinates');
                $wdr=$wdr_mod->where(array('status'=>1))->select();
                if($wdr){
                    $polygon_free='';
                    $polygon_99_top='';
                    $polygon_99_bottom='';
                    $polygon_199='';
                    $polygon_69='';
                    $polygon_299='';
                    $polygon_39='';
                    $polygon_39_c='';
                    $polygon_399='';
                    foreach ($wdr as $key=>$val){
                        if($val['wdtype']==0){
                            $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                            $minwdrc='';
                            if ($wdrc){
                                foreach ($wdrc as $k=>$v){
                                    $polygon_free[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>$val['start_price']);
                                }
                            }else {
                                continue;
                            }
                        }elseif($val['wdtype']==1){
                            $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                            if ($wdrc){
                                foreach ($wdrc as $k=>$v){
                                    $polygon_99_top[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>$val['start_price']);
                                }
                            }else {
                                continue;
                            }
                        }elseif($val['wdtype']==2){
                            $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                            if ($wdrc){
                                foreach ($wdrc as $k=>$v){

                                    $polygon_99_bottom[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>$val['start_price']);
                                }
                            }else {
                                continue;
                            }
                        }elseif($val['wdtype']==3){
                            $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                            if ($wdrc){
                                foreach ($wdrc as $k=>$v){
                                    $polygon_199[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>$val['start_price']);
                                }
                            }else {
                                continue;
                            }
                        }elseif($val['wdtype']==4){
                            $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                            if ($wdrc){
                                foreach ($wdrc as $k=>$v){
                                    $polygon_69[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>$val['start_price']);
                                }
                            }else {
                                continue;
                            }
                        }elseif($val['wdtype']==5){
                            $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                            if ($wdrc){
                                foreach ($wdrc as $k=>$v){
                                    $polygon_299[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>$val['start_price']);
                                }
                            }else {
                                continue;
                            }
                        }elseif($val['wdtype']==6){
                            $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                            if ($wdrc){
                                foreach ($wdrc as $k=>$v){
                                    $polygon_39[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>$val['start_price']);
                                }
                            }else {
                                continue;
                            }
                        }elseif($val['wdtype']==7){
                            $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                            if ($wdrc){
                                foreach ($wdrc as $k=>$v){
                                    $polygon_399[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>$val['start_price']);
                                }
                            }else {
                                continue;
                            }
                        }elseif($val['wdtype']==8){
                            $wdrc=$wdrc_mod->where(array('rid'=>$val['id']))->select();
                            if ($wdrc){
                                foreach ($wdrc as $k=>$v){
                                    $polygon_39_c[$val['id']][]=array('lat'=>$v['latitude'],'lng'=>$v['longitude'],'wid'=>$val['wid'],'wdr_id'=>$val['id'],'name'=>$val['name'],'start_price'=>$val['start_price']);
                                }
                            }else {
                                continue;
                            }
                        }
                    }
                }else{
                    returnApiError('无法匹配到仓库');
                }
                if($polygon_free){
                    foreach ($polygon_free as $key=>$val){
                        foreach ($val as $k=>$v){
                            $free[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                        }
                        $data=$this->isPointInPolygon($free,$longitude,$latitude);
                        if($data){
                            $savedata=array(
                                'wid'=> $free[0]['wid'],
                                'wdr_id'=>$free[0]['wdr_id']
                            );
                            $id=$order_info->where($where)->save($savedata);
                            if($id){
                                return true;
                            }else{
                                returnApiError('订单入仓库失败');
                            }
                        }
                        unset($free);
                        unset($data);
                    }
                }
                if($polygon_99_top){
                    foreach ($polygon_99_top as $key=>$val){
                        foreach ($val as $k=>$v){
                            $top[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                        }
                        $data=$this->isPointInPolygon($top,$longitude,$latitude);
                        if($data){
                            $savedata=array(
                                'wid'=> $top[0]['wid'],
                                'wdr_id'=>$top[0]['wdr_id']
                            );
                            $id=$order_info->where($where)->save($savedata);
                            if($id){
                                return true;
                            }else{
                                returnApiError('订单入仓库失败');
                            }
                        }
                        unset($top);
                        unset($data);
                    }
                }
                if($polygon_99_bottom){
                    foreach ($polygon_99_bottom as $key=>$val){
                        foreach ($val as $k=>$v){
                            $bottom[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price'],'is_day'=>$v['is_day']);
                        }
                        $data=$this->isPointInPolygon($bottom,$longitude,$latitude);
                        if($data){
                            $savedata=array(
                                'wid'=> $bottom[0]['wid'],
                                'wdr_id'=>$bottom[0]['wdr_id']
                            );
                            $id=$order_info->where($where)->save($savedata);
                            if($id){
                                return true;
                            }else{
                                returnApiError('订单入仓库失败');
                            }
                        }
                        unset($bottom);
                        unset($data);
                    }
                }
                if($polygon_199){
                    foreach ($polygon_199 as $key=>$val){
                        foreach ($val as $k=>$v){
                            $p199[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                        }
                        $data=$this->isPointInPolygon($p199,$longitude,$latitude);
                        if($data){
                            $savedata=array(
                                'wid'=> $p199[0]['wid'],
                                'wdr_id'=>$p199[0]['wdr_id']
                            );
                            $id=$order_info->where($where)->save($savedata);
                            if($id){
                                return true;
                            }else{
                                returnApiError('订单入仓库失败');
                            }
                        }
                        unset($p199);
                        unset($data);
                    }
                }
                if($polygon_69){
                    foreach ($polygon_69 as $key=>$val){
                        foreach ($val as $k=>$v){
                            $p69[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                        }
                        $data=$this->isPointInPolygon($p69,$longitude,$latitude);
                        if($data){
                            $savedata=array(
                                'wid'=> $p69[0]['wid'],
                                'wdr_id'=>$p69[0]['wdr_id']
                            );
                            $id=$order_info->where($where)->save($savedata);
                            if($id){
                                return true;
                            }else{
                                returnApiError('订单入仓库失败');
                            }
                        }
                        unset($p69);
                        unset($data);
                    }
                }
                if($polygon_299){
                    foreach ($polygon_299 as $key=>$val){
                        foreach ($val as $k=>$v){
                            $p299[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                        }
                        $data=$this->isPointInPolygon($p299,$longitude,$latitude);
                        if($data){
                            $savedata=array(
                                'wid'=> $p299[0]['wid'],
                                'wdr_id'=>$p299[0]['wdr_id']
                            );
                            $id=$order_info->where($where)->save($savedata);
                            if($id){
                                return true;
                            }else{
                                returnApiError('订单入仓库失败');
                            }
                        }
                        unset($p299);
                        unset($data);
                    }
                }
                if($polygon_39){
                    foreach ($polygon_39 as $key=>$val){
                        foreach ($val as $k=>$v){
                            $p39[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                        }
                        $data=$this->isPointInPolygon($p39,$longitude,$latitude);
                        if($data){
                            $savedata=array(
                                'wid'=> $p39[0]['wid'],
                                'wdr_id'=>$p39[0]['wdr_id']
                            );
                            $id=$order_info->where($where)->save($savedata);
                            if($id){
                                return true;
                            }else{
                                returnApiError('订单入仓库失败');
                            }
                        }
                        unset($p39);
                        unset($data);
                    }
                }
                if($polygon_39_c){
                    foreach ($polygon_39_c as $key=>$val){
                        foreach ($val as $k=>$v){
                            $p39_c[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                        }
                        $data=$this->isPointInPolygon($p39_c,$longitude,$latitude);
                        if($data){
                            $savedata=array(
                                'wid'=> $p39_c[0]['wid'],
                                'wdr_id'=>$p39_c[0]['wdr_id']
                            );
                            $id=$order_info->where($where)->save($savedata);
                            if($id){
                                return true;
                            }else{
                                returnApiError('订单入仓库失败');
                            }
                        }
                        unset($p39_c);
                        unset($data);
                    }
                }
                if($polygon_399){
                    foreach ($polygon_399 as $key=>$val){
                        foreach ($val as $k=>$v){
                            $p399[$k]=array('lat'=>$v['lat'],'lng'=>$v['lng'],'wid'=>$v['wid'],'wdr_id'=>$v['wdr_id'],'name'=>$v['name'],'start_price'=>$v['start_price']);
                        }
                        $data=$this->isPointInPolygon($p399,$longitude,$latitude);
                        if($data){
                            $savedata=array(
                                'wid'=> $p399[0]['wid'],
                                'wdr_id'=>$p399[0]['wdr_id']
                            );
                            $id=$order_info->where($where)->save($savedata);
                            if($id){
                                return true;
                            }else{
                                returnApiError('订单入仓库失败');
                            }
                        }
                        unset($p399);
                        unset($data);
                    }
                }
                returnApiError('订单入仓库失败');
            }else{
                returnApiError('按配送区域无法自动分派仓库');
            }
        }else{
            returnApiError('查无此订单');
        }    }
    
    /*TODO 根据ID获取区域对应名称*/
    public  function get_region_name($id){
    	$res=M('region')->where(array('region_id'=>$id))->find();
    	return $res['region_name'];
    }
    /*
     * TODO 检查配送员是否合法,合法返回数组
     * */
    public function check_warehouse_personnel($uid){
    	$res=M('warehouse_personnel')->where(array('uid'=>$uid,'status'=>1))->find();
    	if($res['uid']){
    		return $res;
    	}else{
    		return false;
    	}
    }
    
    /*
     * TODO 根据后台用户ID获取当前用户数据
     * */
    public function get_admin_user_name($uid){
    	$res=M('admin_user')->where(array('user_id'=>$uid))->find();
       if($res){
		   $res['phone'] = M('warehouse_personnel')->where(array('uid'=>$uid))->getField('phone');
		   $res['name'] = M('warehouse_personnel')->where(array('uid'=>$uid))->getField('name');
		   if(!empty($res['name'])){
			   $res['user_name'] = $res['name']." [ ".$res['user_name']." ]";
		   }
//		   dump(M('warehouse_personnel')->getlastsql());
//		   dump($res);
    		return $res;
    	}else{
    		return false;
    	}
    }
    
    /*
     * TODO 记录配送员操作日志
     * */
    public function record_diliveryman_log($a=array()){
    	$data['order_id']=$a['order_id'];
    	$user=$this->get_admin_user_name($a['user_id']);
    	if(!$user){
    		return false;
    	}
        $wp=$this->check_warehouse_personnel($a['user_id']);
        $data['con_phone'] = $wp['phone'];

        $juese='';
    	if($wp){
    		$data['longitude'] = $wp['longitude'];
    		$data['latitude'] = $wp['latitude'];
    		
    		if($wp['position']==1){
    			$juese='配货员';
    		}elseif ($wp['position']==2){
    			$juese='配送员';
    		}elseif ($wp['position']==3){
				$juese='仓管员';
			}
    	}
    	if($wp['phone']){
    		$data['action_user']=$wp['name']."[.".$user['user_name']."]——角色：".$juese."   ".$wp['phone'];
    	}else{
    		$data['action_user']=$wp['name']."[.".$user['user_name']."]——角色：".$juese;
    	}
    	$data['order_status']=$a['order_status'];
    	$data['shipping_status']=$a['shipping_status'];
    	$data['pay_status']=$a['pay_status'];
    	$data['action_place']=0;
    	$data['action_note']=$a['action_note'];
        $data['action_type'] = empty($a['action_type']) ? 0 : $a['action_type'] + 0;    //预警类型
    	
    	$data['log_time']=gmtime();
//        print_r($data);die;
    	M('order_action')->add($data);
    }


    /**
     * TODO 插入预警单
     * @param $order_sn
     * @param int $type
     * @return mixed
     */
    protected function alarm_log($order_sn, $type=6)
    {
        $data = array(
            'order_sn'      =>  $order_sn,
            'type'          =>  $type,
            'trigger_time'  =>  time(),
        );
        return M('alarm_log')->add($data);
    }
    
    /**
     * TODO 射线法计算坐标是否在规定图形内
     * @param $polygon
     * @param $longitude
     * @param $latitude
     * @return bool
     */
    private function isPointInPolygon($polygon, $longitude, $latitude){
        $count = count($polygon);
        $px = $longitude;
        $py = $latitude;
        $flag = false;
        for ($i = 0, $j = $count - 1; $i < $count; $j = $i, $i++) {
            $sy = $polygon[$i]['lng'];
            $sx = $polygon[$i]['lat'];
            $ty = $polygon[$j]['lng'];
            $tx = $polygon[$j]['lat'];
            if ($px == $sx && $py == $sy || $px == $tx && $py == $ty)
            {
                return true;
            }
            if ($sy < $py && $ty >= $py || $sy >= $py && $ty < $py) {
                $x = $sx + ($py - $sy) * ($tx - $sx) / ($ty - $sy);
                if ($x == $px){
                    return true;
                }
                if ($x > $px){
                    $flag = !$flag;
                }
    
            }
        }
        return $flag;
    }


	/**
	 *更改订单的收获时间
	 * todo 延迟订单
     */
	public function change_distribution_time(){
		$order_id=I('post.order_id','intval');
		$distribution_time=I('post.distribution_time','');
		$user_id = I('post.user_id','intval');
		$is_shipping_app =  I('post.is_shipping_app','intval');
		$next_monday =  I('post.next_monday',0, 'int');
		$remark =  I('post.remark','');
		$remark =  str_replace(" ",'',$remark);
		$deploy_info = $this->get_admin_user_name($user_id);
		//判断用户类型1 配货员  2配送员
		$wprow=M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('position');

		
		if(empty($order_id)){
			returnApiError('订单ID/配送时间为空');
		}else{

			$map = array("order_id"=>$order_id);
			$order = M('order_info')->field('pay_status,order_id,wid,user_id,order_sn,mobile,consignee,best_time,best_time_start,order_status,shipping_status,is_presell')->where($map)->find();
			if($next_monday!=1){
				$shipping_arrive_time = explode('-', $distribution_time);
				$data['best_time_start'] = $shipping_arrive_time[0];
				$data['best_time'] = $shipping_arrive_time[1];

			}else{
				//
				$data['best_time_start'] = strtotime(date('Y-m-d',strtotime('+1 week last monday'))." 10:00:00");
				$data['best_time'] = strtotime(date('Y-m-d',strtotime('+1 week last monday'))." 22:00:00");
			}

			$dtime=time();
			$dftime=date('Y-m-d',$dtime);
			$order_best_time=date('Y-m-d',$data['best_time']);

			$huic_test = "";

			if($wprow==1){
				//配货延迟，更改为未发货，并删除配货员ID
				if($order_best_time!=$dftime) {
					$data['shipping_status'] = 0;
					$data['sorting_id'] = 0;
					$data['wp_userid'] = 0;
				}
				$action_note = $remark."//已延迟配货";
			}else if ($wprow==2){
				//配送员延迟 更改为 配货完成  并删除配送员ID
				if($order_best_time!=$dftime) {
					$data['shipping_status'] = 5;
					$data['wp_userid'] = 0;
					//$data['outgo']=2;	    //商品需要回仓
					//$data['sorting_id'] = 0;
				}
				$action_note = $remark."//已延迟配送";
			}else{
				returnApiError("用户角色ID不正常");
			}

			$diff_time = date('d',$data['best_time_start'])-date('d',$order['best_time_start']);
			


			//修改期望送达时间
			$action_note .= " 由 [".date('Y-m-d H:i:s',$order['best_time_start'])."] - [".date('Y-m-d H:i:s',$order['best_time'])."]";

			$action_note .= " 延迟至 [".date('Y-m-d H:i:s',$data['best_time_start'])."] - [".date('Y-m-d H:i:s',$data['best_time'])."]";


			$change_order =  false;

			if(($order_best_time!=$dftime)&&$wprow==1){
				//配货员延迟到次日，改预售单
				$change_order =  true;
			}
			if(($wprow==2)&&($diff_time>1)){
				//配送员延迟两天以上，改预售单
				$data['shipping_status'] = 0;
				$data['wp_userid'] = 0;
				$data['sorting_id'] = 0;
				$data['sorting_time'] = 0;
				$change_order =  true;
				$data['outgo'] = 2;
				$huic_test = "<span style='color: #ff0000;'>订单需要回仓，请将商品拿回总仓</span>";
			}

			if($change_order){

				//将处理现售商品
				$goods_list =M("order_goods")->where(array("order_id"=>$order_id))->select();
				if(count($goods_list)>0){
					$rdgoods=array();
					//处理退货退款的商品
					$rdsql='select goods_id,SUM(refund_number) as refund_number from sdx_refund_detail where order_id='.$order_id.' group by goods_id';
					$rdlist=M()->query($rdsql);
					if($rdlist){
						foreach ($rdlist as $key=>$val){
							$rdgoods[$val['goods_id']]=$val['refund_number'];
						}
					}

					foreach ($goods_list as $k=>$v){
						$goods_morrow=M("goods")->where(array("goods_id"=>$v['goods_id']))->getField('is_auto_morrow_presell');
						if($v['is_presell']==0 && $goods_morrow){  //有启用“次日达自动预售”的现售商品
							$goodsstorage = M("goods_storage")->field("id,wid,goods_id,goods_sn,goods_name,practical_num,freeze_num,inferior_quality_num")->where(array("wid"=>$order['wid'],"goods_id"=>$v['goods_id']))->find();
							if ($goodsstorage) {
								M("order_goods")->where(array("rec_id"=>$v['rec_id']))->setField("is_presell",1);
								if(!empty($rdgoods[$v['goods_id']])){
									$refund_number=$rdgoods[$v['goods_id']];
									$v['goods_number']=$v['goods_number']-$refund_number;
								}
								$practical_num = $goodsstorage['practical_num'] + $v['goods_number'];
								$freeze_num = $goodsstorage['freeze_num'] - $v['goods_number'];
								/* 商品实际库存+ 商品冻结库存- */
								$goods_storage_sql = "UPDATE sdx_goods_storage
                                    SET practical_num = " . $practical_num . ",freeze_num=" . $freeze_num .
									" WHERE wid = " . $goodsstorage['wid'] . " and goods_id=" . $v['goods_id'];

								M()->execute($goods_storage_sql);
								/* 生成商品实际出入库记录 */
								$goods_storage_record_sql = "INSERT INTO sdx_goods_storage_record
									(goods_storage_id,wpid,wid,goods_id,goods_sn, " .
									"operation_num, real_num, frozen_num, defective_num, " .
									"operation_userid, average_userid, operation_addtime, source_no,record_type,remark) VALUES (" .
									$goodsstorage['id'] . ",0," . $goodsstorage['wid'] . "," . $goodsstorage['goods_id'] . ",'" . $goodsstorage['goods_sn'] . "'," .
									$v['goods_number'] . "," . $practical_num . ",0,0,0," . $order['user_id'] . "," . gmtime() . ",'" . $order['order_sn'] . "',17,'在仓回流')";
								M()->execute($goods_storage_record_sql);
								/* 生成商品冻结出入库记录 */
								$freeze_sql = "INSERT INTO sdx_goods_freeze_record
									(goods_storage_id,wid,goods_id,goods_sn,goods_name," .
									"freeze_num, real_num, frozen_num, defective_num, " .
									"operation_userid, average_userid, operation_addtime, source_no,record_type,remark) VALUES (" .
									$goodsstorage['id'] . "," . $goodsstorage['wid'] . "," . $goodsstorage['goods_id'] . ",'" . $goodsstorage['goods_sn'] . "','" .
									$goodsstorage['goods_name'] . "'," . $v['goods_number'] . ",0," . $freeze_num . ',0,0,' . $order['user_id'] . "," . gmtime() . ",'" . $order['order_sn'] . "',14,'在仓回流')";
								M()->execute($freeze_sql);
								$new_order_xx['shipping_status']=SS_UNSHIPPED;//修改订单配送状态为未发货
								$new_order_xx['is_presell']=1;

								M("order_info")->where(array("order_id"=>$order_id))->save($new_order_xx);
								//
								$note='该商品有启用“次日达自动预售”的现售<br />商品货号:('.$v['goods_sn'].'-ID:'.$v['goods_id'].')进行现售变预售';
								$new_data['order_id'] = $order['order_id'];
								$new_data['order_status'] = $order['order_status'];
								$new_data['shipping_status'] = SS_UNSHIPPED;
								$new_data['pay_status'] = $order['pay_status'];
								$new_data['action_note'] = $note;
								$new_data['action_user'] = $deploy_info['user_name']." [ ".$deploy_info['phone']." ] ";
								$new_data['log_time'] = gmtime();
								M("order_action")->add($new_data);
							}else{
								continue;
							}
						}
					}
				}




			}
			$re = M('order_info')->where($map)->save($data);
			//dump(M('order_info')->getlastsql());
			$a = array (
					'order_id' => $order_id,
					'user_id' => $user_id,
					'order_status' => OS_CONFIRMED,
					'shipping_status' => $data['shipping_status'],
					'pay_status' => PS_PAYED,
					'action_note' => $action_note."</br>".$huic_test
			);
			$this->record_diliveryman_log ( $a ); // 记录配送员操作日志

			if($wprow==2){
				//从配送群组中清除
				if($is_shipping_app && $re!==false){
					M('warehouse_deliver_order_group')->where($map)->delete();
				}
			}elseif ($wprow==1){
				//从配送群组中删除
				$where['state']=0;
				$where['user_id']=$user_id;
				$count=M('sorting_order_group')->where($where)->select();
				foreach ($count as $key=>$value){
					$array_list = explode(",",$value['order_id']);
					foreach ($array_list as $key_2=>$value_2){
						if($value['order_id'] ==$value_2){
							unset($array_list[$key_2]);
							M("sorting_order_group")->where("id=".$value['id'])->setField('order_id',implode(",",$array_list));
							break;
						}
					}

//					if(in_array($order_id,$array_list)){
//						//存在，删除此订单号
//
//					}
				}


			}

			$datetime = date("Y-m-d",$data['best_time_start']);
			$smsremark['best_time'] = $datetime.' '.date("H:i:s",$data['best_time_start']).'-'.date("H:i:s",$data['best_time']);

			//发送短信通知
			$send_result = A("Smsapi")->send_message_api('delayed_delivery_notice',$order['mobile'],$order['consignee'],0,$order['order_sn'],0,$order['user_id'],$smsremark);
			
			if($re){
//
//				if($order_best_time!=$dftime){
//					returnApiError('延迟成功,商品需拿回总仓');
//				}



				returnApiSuccess(null,'change success');
			}else{
				returnApiError('change fail');
			}
		}
	}
    
	/**
	 * TODO 问题订单提交
	 */
	public function describe_order(){
		$user_id = I('post.user_id');
		$order_id = I('post.order_id');
		$content = I('post.content');
		$content =  str_replace(" ",'',$content);
		$is_shipping_app =  I('post.is_shipping_app','intval');
		
		if(empty($user_id)){
			returnApiError('参数错误');
		}
		if(empty($order_id)){
			returnApiError('参数错误');
		}
		if(empty($content)){
			returnApiError('参数错误');
		}
		
		$wp=$this->check_warehouse_personnel($user_id);

		if(!$wp){
			returnApiError('非法用户或者该用户已被禁用');
		}

		$map = array('order_id'=>$order_id);
		$order = M('order_info')->field('wp_userid,sorting_id,best_time_start,best_time,user_id,order_sn,mobile,consignee,order_sn,order_status,shipping_status')->where($map)->find();
		
		if($order['order_status']==OS_CONFIRMED && $order['shipping_status']==SS_UNSHIPPED){
			returnApiError('此订单已提交问题单处理，请勿重复操作');
		}


		$wprow=M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('position');

		if($wprow==1){
			//配货延迟，更改为未发货，并删除配货员ID
				$data['shipping_status'] = 0;
				$data['sorting_id'] = 0;
				$data['wp_userid'] = 0;
		}else if ($wprow==2){
			//配送员延迟 更改为 配货完成  并删除配送员ID
				$data['shipping_status'] = 5;
				$data['wp_userid'] = 0;
				//$data['outgo']=2;	    //商品需要回仓
				//$data['sorting_id'] = 0;
		}
		else{
			returnApiError("用户角色ID不正常");
		}


        $data['best_time_start'] = strtotime(date("Y-m-d", strtotime('+1 days'))." 10:00:00");
        $data['best_time'] = strtotime(date("Y-m-d", strtotime('+1 days'))." 12:00:00");


		$re = M('order_info')->where($map)->save($data);
		$order_data = M('order_info')->where($map)->find();

		$a = array (
				'order_id' => $order_id,
				'user_id' => $user_id,
				'order_status' => $order_data['order_status'],
				'shipping_status' => $order_data['shipping_status'],
				'pay_status' => $order_data['pay_status'],
				'action_note' => $content."//问题单提交 - 订单配送时间由".date("Y-m-d H:i:s",$order['best_time_start'])."-".date("Y-m-d H:i:s",$order['best_time'])." 延迟至".date("Y-m-d H:i:s",$data['best_time_start'])."-".date("Y-m-d H:i:s",$data['best_time']),
                'action_type'   =>  OA_WRONG,
		);
		$this->record_diliveryman_log( $a ); // 记录配送员操作日志

		if($is_shipping_app && $re!==false){
			M('warehouse_deliver_order_group')->where($map)->delete();
		}

		//发送短信通知
        $send_result = A("Smsapi")->send_message_api('describe_order_notice',$order['mobile'],$order['consignee'],0,$order['order_sn'],0,$order['user_id']);

//        问题单
//        $this->alarm_log($order['order_sn']);

		if($re){
			returnApiSuccess(null,'change success');
		}else{
			returnApiError('change fail');
		}
		
		
	}
	
	/*TODO 创建配送群组*/
    public function group_create(){
    	if(!IS_POST){
    		returnApiError('error request');
    	}
        $user_id=I('post.user_id','intval');
        $order_id_list  = I('post.order_id_list');
        $name = I('post.name');
        
        if(empty($user_id)){
        	returnApiError('参数错误');
        }
        if(empty($order_id_list)){
        	returnApiError('参数错误');
        }
        if(empty($name)){
        	returnApiError('参数错误');
        }
        
        $wp=$this->check_warehouse_personnel($user_id);
        
        if(!$wp){
        	returnApiError('非法用户或者该用户已被禁用');
        }
        
        $group_id = $this->create_order_group($user_id, $name);
        if($group_id){
        	//将配送订单加入到群组
        	$result = $this->add_to_group($group_id, $order_id_list,$user_id);
        	
        	$map = array('go.group_id'=>$group_id);
        	$order_info = M('order_info');
        	$order_list = $order_info->alias('o')->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')->field('o.user_id as user_id,o.order_id as order_id,o.order_sn as order_sn,o.mobile as mobile,o.consignee as consignee,o.best_time as best_time,o.best_time_start,go.take_no as take_no')->where($map)->select();
        	
        	$remark['phone'] = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('phone');
        	//发送短信
        	foreach ($order_list as $order){
	        	if($order['best_time_start']==0){            	
	            	if($order['is_presell']==1){
	            		$new_best_time = date("Y-m-d",$order['best_time'])." 20:30:00";
	            		$order['best_time'] = strtotime($new_best_time)-1;
	            		$order['best_time_start'] = strtotime(date("Y-m-d",$order['best_time'])." 10:00:00");
	            	}else{
	            		$order['best_time_start'] = $order['best_time']-2*3600;
	            	}
	            }
        		$datetime = date("Y-m-d",$order['best_time_start']);

        		$remark['best_time'] = $datetime.' '.date("H:i:s",$order['best_time_start']).'-'.date("H:i:s",$order['best_time']);
        		
        		$send_result = A("Smsapi")->send_message_api('shipping_start_notice',$order['mobile'],$order['consignee'],0,$order['order_sn'],0,$order['user_id'],$remark);
        	}
        	$result['error_code'] = 100;
        	returnApiSuccess($result,'创建群组成功');
        }else{
        	returnApiError('创建群组失败，请重试');
        }
    }
    
    private function create_order_group($user_id,$group_name){
    	$data = array();
    	$data['user_id'] = $user_id;
    	$data['name'] = $group_name;
    	$data['create_time'] = gmtime();
    	$group_id = D('warehouse_deliver_group')->add($data);
    	
    	if(!$group_id){
    		returnApiError('创建群组失败，请重试');
    	}
    	return $group_id;
    }
    
    private function add_to_group($group_id,$order_id_list,$user_id){
    	$group_order_list = array();
    	$order_id_list = explode(',', $order_id_list);
    	//过滤已经是配送中的order
    	$order_info = D('order_info');
    	//获取待配送的订单，order_status=>1,shipping_status->3
    	$no_delier_orderid_list = $order_info->where(array('order_id'=>array('in',$order_id_list),'order_status'=>array('neq','2'),'shipping_status'=>5,'pay_status'=>array('EGT',PS_PAYED)))->getField('order_id',true);
    	//将待配送的订单加入到群组中，并修改状态为配送中
    	
    	//获取当前群组订单格式，take_no在此基础上增加
    	$deliver_order_group =  D('warehouse_deliver_order_group');
    	$count = $deliver_order_group->where(array('group_id'=>$group_id))->count();
    	if($count>0){
    		$take_no = $count +1;
    	}else{
    		$take_no = 1;
    	}
    	foreach ($no_delier_orderid_list as $order_id){
    		$order_data = array();
    		$order_data['group_id'] = $group_id;
    		$order_data['order_id'] = $order_id;
    		$order_data['take_no'] = $take_no;
    		$group_order_list[] = $order_data;
    		$take_no++;
    	}
    	if(count($group_order_list)>0){
    		$res = $deliver_order_group->addAll($group_order_list);
    		if($res){
    			//修改配送订单状态为配送中
    			$where = array('order_id'=>array('in',$no_delier_orderid_list));
    			D('warehouse_deliver_order')->where($where)->setField('order_status',1);
    			//修改订单状态为已发货
    			$savedata = array();
    			$savedata['order_status']=OS_SPLITED;
    			$savedata['shipping_status']=SS_SHIPPED;
    			$data['shipping_time']=gmtime();
    			D('order_info')->where($where)->save($savedata);
//     			$order_list = M('order_info')->where(array('order_id'=>array('in',$order_id_list)))->select();
    			
    			foreach ($no_delier_orderid_list as $order_id){
    				//记录配送员操作日志
    				$act=array(
    						'order_id'=>$order_id,
    						'user_id'=>$user_id,
    						'order_status'=>OS_SPLITED,
    						'shipping_status'=>SS_SHIPPED,
    						'pay_status'=>PS_PAYED,
    						'action_note'=>'已发货'
    				);
    				$this->record_diliveryman_log($act);
    			}
    			$result['error_code']=100;
    			return $result;
    		}else{
    			returnApiError('配送订单加入群组失败');
    		}
    	}else{
    		returnApiError('没有待配送订单');
    	}
    }

	/**
	 *TODO 群组列表
     */
	public function group_list(){
    	if(!IS_POST){
    		returnApiError('error request');
    	}
    	$user_id=I('post.user_id','intval');
    	$page  = I('post.page','intval');
    	
    	if(empty($user_id)){
    		returnApiError('参数错误');
    	}
    	if(empty($page)){
    		returnApiError('参数错误');
    	}
    	
    	$wp=$this->check_warehouse_personnel($user_id);
    	
    	if(!$wp){
    		returnApiError('非法用户或者该用户已被禁用');
    	}
    	
    	$map = array('user_id'=>$user_id,'status'=>1);
    	$deliver_group = M('warehouse_deliver_group');
    	$count = $deliver_group->where($map)->count();
    	$pagearr=show_page($count, $page);
    	if($page>=$pagearr['pagecount']){
    		$is_last=1;
    	}else{
    		$is_last=0;
    	}
    	
    	$list = $deliver_group->where($map)->limit($pagearr['firstpage'],$pagearr['pagesize'])->order('create_time asc')->select();
    	if($list){
    		foreach ($list as $key=>$group){
    			$count =M('warehouse_deliver_order_group')->where(array('group_id'=>$group['group_id']))->count();
    			$list[$key]['count'] = $count;
    		}
    		$result = array('list'=>$list,'is_last'=>$is_last);
    		returnApiSuccess($result);
    	}else{
    		returnApiError('没有数据');
    	}
    }
    
    public function group_sub_list(){
    	if(!IS_POST){
    		returnApiError('error request');
    	}
    	
    	$user_id=I('post.user_id','intval');
    	$group_id = I('post.group_id','intval');
    	$page  = I('post.page','intval');
    	 
    	if(empty($user_id)){
    		returnApiError('参数错误');
    	}
    	if(empty($group_id)){
    		returnApiError('参数错误');
    	}
    	if(empty($page)){
    		returnApiError('参数错误');
    	}
    	 
    	$wp=$this->check_warehouse_personnel($user_id);
    	 
    	if(!$wp){
    		returnApiError('非法用户或者该用户已被禁用');
    	}
    	
    	$id = D('warehouse_deliver_group')->where(array('group_id'=>$group_id,'user_id'=>$user_id))->getField('group_id');
    	if(empty($id)){
    		returnApiError('此群组不存在或不是该用户创建的');
    	}
    	$map = array('go.group_id'=>$group_id);
    	$deliver_order = M('order_info');
    	
    	$count = $deliver_order->alias('o')->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')->where($map)->count();
    	$pagearr=show_page($count, $page);
    	if($page>=$pagearr['pagecount']){
    		$is_last=1;
    	}else{
    		$is_last=0;
    	}
    	
    	if($count){
    		$field = 'o.order_id,o.order_sn as order_num,o.order_status as order_status,o.shipping_status as shipping_status,o.add_time as order_time,o.consignee as name,o.mobile as phone,o.country as country,o.province as province,o.city as city,o.district as district,o.address as address,o.sign_building as sign_building,o.address_name as address_name,go.take_no as take_no';
    		$list = $deliver_order->alias('o')->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')->field($field)->where($map)->order('go.take_no asc')->limit($pagearr['firstpage'],$pagearr['pagesize'])->select();
    		if(!empty($list)){
    			$order_goods = M('order_goods');
    			foreach ($list as $key=>$data){
    				$country_name=$this->get_region_name($data['country']);
    				$province_name=$this->get_region_name($data['province']);
    				$city_name=$this->get_region_name($data['city']);
    				$district_name=$this->get_region_name($data['district']);
    				$list[$key]['address']=$country_name.$province_name.$city_name.$district_name.$data['address'].$data['sign_building'].$data['address_name'];
    				$list[$key]['order_time']=date('Y-m-d H:i:s',$data['order_time']+(8*3600));
    				
    				if($data['order_status'] == OS_SPLITED && $data['shipping_status'] == SS_RECEIVED){
    					$list[$key]['order_state']=2;
    				}else{
    					$list[$key]['order_state']=1;
    				}
    				
    				$goods=$order_goods->field('goods_sn as goods_number,goods_id as id,goods_name as name,goods_price as price,goods_number as `count`')->where(array('order_id'=>$data['order_id']))->select();
    				$list[$key]['goods_list'] = $goods;
    			}
    			$result = array('list'=>$list,'is_last'=>$is_last);
    			returnApiSuccess($result);
    		}else{
    			returnApiError('没有数据');
    		}
    	}else{
    		returnApiError('没有数据');
    	}
    }

	/**
	 * TODO 群组完成
     */
	public function group_distributed(){
    	if(!IS_POST){
    		returnApiError('error request');
    	}
    	 
    	$user_id=I('post.user_id','intval');
    	$group_id = I('post.group_id','intval');
    	
    	if(empty($user_id)){
    		returnApiError('参数错误');
    	}
    	if(empty($group_id)){
    		returnApiError('参数错误');
    	}
    	
    	$wp=$this->check_warehouse_personnel($user_id);
    	
    	if(!$wp){
    		returnApiError('非法用户或者该用户已被禁用');
    	}
    	
    	$id = D('warehouse_deliver_group')->where(array('group_id'=>$group_id,'user_id'=>$user_id))->getField('group_id');
    	if(empty($id)){
    		returnApiError('此群组不是该用户创建的');
    	}
    	$map = array('go.group_id'=>$group_id);
//    	$deliver_order = M('warehouse_deliver_order');
//    	$order_list = $deliver_order->alias('o')
//    	              ->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')
//    	              ->join('inner join '.C('DB_PREFIX').'order_info oi on oi.order_id = o.order_id')
//    	              ->field('DISTINCT( o.order_id) as order_id,o.user_id as user_id,o.order_consignee_phone as mobile,o.order_consignee_name as consignee,o.order_sn as order_sn,oi.wid,oi.order_status as order_status,oi.shipping_status as shipping_status,oi.pay_status as pay_status')
//    	              ->where($map)
//    	              ->select();
		$deliver_order = M('order_info');
		$order_list = $deliver_order->alias('o')
    	              ->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')
    	              ->field('DISTINCT( o.order_id) as order_id,o.user_id as user_id,o.mobile,o.consignee,o.order_sn,o.wid,o.order_status,o.shipping_status,o.pay_status')
    	              ->where($map)
    	              ->select();
    	if(!empty($order_list)){
    		$order_ids = array();
    		foreach ($order_list as $key=>$order){
	    		if($order['order_status']==5 && $order['shipping_status']==2){
	    			unset($order_list[$key]);
	        		continue;
	        	}
    			$order_ids[]= $order['order_id'];
    			/* 收货确认减冻结库存*/
    			$this->order_buckle_inventory($order);
    		}
    		
    		if(count($order_ids)>0){
    			$where = array('order_id'=>array('in',$order_ids));
    			 
    			//修改订单状态为已发货
    			$savedata = array();
    			$savedata['order_status']=OS_SPLITED;
    			$savedata['shipping_status']=SS_RECEIVED;
    			$savedata['confirm_time']=gmtime();
    			$savedata['wp_userid']=$user_id;
    			D('order_info')->where($where)->save($savedata);
    			 
    			//修改配送订单状态为已配送
    			D('warehouse_deliver_order')->where($where)->setField('order_status',2);
    			foreach ($order_ids as $o_id){
    				$a = array (
    						'order_id' => $o_id,
    						'user_id' => $user_id,
    						'order_status' => OS_SPLITED,
    						'shipping_status' => SS_RECEIVED,
    						'pay_status' => PS_PAYED,
    						'action_note' => '配送完成,收货确认'
    				);
    				$this->record_diliveryman_log ( $a ); // 记录配送员操作日志
    			}
    			
    			foreach ($order_list as $key=>$v){
    				//发送订单配送完成短信给收货人
    				$send_result = A("Smsapi")->send_message_api('order_finish',$v['mobile'],$v['consignee'],0,$v['order_sn'],0,$v['user_id']);
    			}
    		}
    	}
    	
    	$map = array('group_id'=>$group_id);
    	//修改群组状态
    	$deliver_group = D('warehouse_deliver_group');
    	$savedata['end_state'] = 1;
    	$savedata['status'] = 0;
    	$res = $deliver_group->where($map)->save($savedata);
    	
    	returnApiSuccess ( '', '收货确认成功' );    	
    }

	/**
	 * TODO 工作中心
     */
	public function work_info(){
    	$user_id=I('post.user_id','intval');
    	
    	if(empty($user_id)){
    		returnApiError('参数错误');
    	}
    	
    	$wp=$this->check_warehouse_personnel($user_id);
    	
    	if(!$wp){
    		returnApiError('非法用户或者该用户已被禁用');
    	}
    	
    	$userinfo = M('warehouse_personnel')->field('uid,phone,wid')->where(array('uid'=>$user_id))->find();
		$phone = $userinfo['phone'];
    	//获取当天日期
    	$curdate = date("Y-m-d");
    	//获取当月日期
    	$curmonth = date("Y-m");
    	//日订单量
    	$day_order_count = $this->get_day_order_count($curdate, $user_id);
    	//日平均分单量
		$day_order_count_avg = $this->get_day_order_count_avg($curdate,$userinfo['wid']);
		//月订单量
		$month_order_count = $this->get_month_order_count($curmonth,$user_id);
		//扫单准点率
		$scan_accurate = $this->get_scan_accurate($curmonth,$user_id);
		//送达准点率
		$arrived_accurate = $this->get_arrived_accurate($curmonth,$user_id);
    	
		$result = array();

		$result['user_id'] = $user_id;
		$result['phone'] = $phone;
		$result['day_order_count'] = $day_order_count;
		$result['day_order_count_avg'] = $day_order_count_avg;
		$result['month_order_count'] = $month_order_count;
		$result['scan_accurate'] = $scan_accurate;
		$result['arrived_accurate'] = $arrived_accurate;
		
		returnApiSuccess ($result);
    }
    
    /*
     * TODO 日订单量，显示该配送员当日的配送订单量
     */
    private function get_day_order_count($date,$uid=0){
    	$begintime = strtotime($date);
    	$endtime = strtotime($date." 23:59:59");
    	if($uid){
    		$map['wp_userid'] = $uid;
    	}
    	$map['confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
    	//$map['order_status']=OS_SPLITED;
    	$map['shipping_status']=SS_RECEIVED;
    	$count = M('order_info')->where($map)->count();
    	
    	return $count;
    }
    
    /*
     * TODO 日平均分单量，显示当日该门店的配送员平均分单量，每小时更新
     */
    private function get_day_order_count_avg($curdate,$wid=0){
    	$begintime = strtotime($curdate);
    	$endtime = strtotime($curdate." 23:59:59");
		
    	$map = array();
    	$map['o.confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
    	//$map['o.order_status']=OS_SPLITED;
    	$map['o.shipping_status']=SS_RECEIVED;
    	
    	$user_map = array();
    	$user_map['status'] = 1;
    	if($wid){
    		$map['p.wid'] = $wid;
    		$user_map['wid']=$wid;
    	}
    	$order_info = M('order_info');
    	$count = $order_info->alias('o')->field('distinct(order_id)')->join("left join ".C('DB_PREFIX')."warehouse_personnel p on o.wp_userid = p.uid")->where($map)->count();
    	$user_count = M('warehouse_personnel')->where($user_map)->count();
    	$count_avg = round($count/$user_count,2);
    	return $count_avg;
    }
    
    /*
     * TODO 月订单量，显示该配送员个人该月订单量。点击可进入“历史订单”
     * user_id为0则为月总订单量
     */

    private function get_month_order_count($curmonth,$user_id=0){
    	$begintime = strtotime($curmonth.'-01 00:00:00')-28800;
        $lastday = date('Y-m-d', strtotime("$curmonth +1 month -1 day"));
    	$endtime = strtotime($lastday." 23:59:59")-28800;

   		if($user_id){
    		$map['wp_userid'] = $user_id;
    	}
    	$map['confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
    	//$map['order_status']= array('neq',2);
    	$map['shipping_status']= 2;
        //$map['pay_status'] = array("in","2,3");
    	$count = M('order_info')->where($map)->count();
    	return $count;
    }
    /*
     * 扫单准点率：扫单率=（准扫单量/订单总量）*100%，漏单量=扫单发货时间超过用户期望最早时间点。
     */
    private function get_scan_accurate($curmonth,$user_id){
    	$sum_count = $this->get_month_order_count($curmonth,$user_id);
    	$punctual_count = $this->get_punctual_order_count($curmonth, $user_id);
    	
    	$rate = round($punctual_count/$sum_count*100,2)."%";
    	return $rate;
    }
    
    /*
     * 准扫单量
     */
    private function get_punctual_order_count($curmonth,$user_id){
    	$begintime = strtotime($curmonth.'-1');
    	$days = date('t',strtotime($curmonth));
    	$endtime = strtotime($curmonth.'-'.$days." 23:59:59");
    	
    	if($user_id){
    		$map['wp_userid'] = $user_id;
    	}
    	$map['confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
    	$map['_string'] = "shipping_time<=(best_time-2*3600)";
    	$map['order_status']=OS_SPLITED;
    	$map['shipping_status']=SS_RECEIVED;
    	$count = M('order_info')->where($map)->count();
    	
    	return $count;
    }
    
    /*
     * 送达准点率，（准点送达订单量/订单总量）*100%，未准点送达=没有在用户期望时间段内确认收货的订单。
     */
    private function get_arrived_accurate($curmonth,$user_id){
    	$sum_count = $this->get_month_order_count($curmonth,$user_id);
    	$arrived_count = $this->get_arrived_count($curmonth,$user_id);
    	$rate = round($arrived_count/$sum_count*100,2)."%";
    	return $rate;
    }
    
    /*
     * 准点送达订单量
     */
    private function get_arrived_count($curmonth,$user_id){
    	$begintime = strtotime($curmonth.'-1');
    	$days = date('t',strtotime($curmonth));
    	$endtime = strtotime($curmonth.'-'.$days." 23:59:59");
    	 
    	if($user_id){
    		$map['wp_userid'] = $user_id;
    	}
    	$map['confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
    	$map['order_status']=OS_SPLITED;
    	$map['shipping_status']=SS_RECEIVED;
    	$map['_string'] = "confirm_time<=best_time";
    	$count = M('order_info')->where($map)->count();
    	 
    	return $count;
    }

	/**
	 * TODO 群组发送信息
     */
	public function group_send_msg(){
    	if(!IS_POST){
    		returnApiError('error request');
    	}
    	$user_id=I('post.user_id','intval');
    	$group_id = I('post.group_id','intval');
    	$meet_time = I('post.meet_time','intval');
    	$meet_address = I('post.meet_address');

    	if(empty($user_id)){
    		returnApiError('参数错误');
    	}
    	if(empty($group_id)){
    		returnApiError('参数错误');
    	}
    	
    	if(empty($meet_time)){
    		returnApiError('meet_time参数错误');
    	}
    	if(empty($meet_address)){
    		returnApiError('meet_address参数错误');
    	}
    	
    	 
    	$wp=$this->check_warehouse_personnel($user_id);
    	 
    	if(!$wp){
    		returnApiError('非法用户或者该用户已被禁用');
    	}
    	
    	$map = array('go.group_id'=>$group_id);
    	$order_info = M('order_info');
    	$order_list = $order_info->alias('o')->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')->field('o.user_id as user_id,o.order_id as order_id,o.order_sn as order_sn,o.mobile as mobile,o.consignee as consignee,go.take_no as take_no')->where($map)->select();
    	
    	//发送短信
    	$remark = array('');
    	$remark['meet_time']= $meet_time;
    	$remark['meet_address'] = $meet_address;
    	$remark['phone'] = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('phone');
    	
    	foreach ($order_list as $order){
    		$remark['take_no'] = $order['take_no'];
    		$send_result = A("Smsapi")->send_message_api('shipping_pickup_notice',$order['mobile'],$order['consignee'],0,$order['order_sn'],0,$order['user_id'],$remark);
    	}
    	
    	$where = array('group_id'=>$group_id);
    	//修改群组状态
    	$deliver_group = D('warehouse_deliver_group');
    	$deliver_group->where($where)->setField('send_state',1);
    	 
    	$deliver_group_info = $deliver_group->where($where)->find();
    	 
    	//如果配送完成修改群组状态
    	if($deliver_group_info['end_state']==1){
    		$deliver_group->where($where)->setField('status',0);
    	}
    	
    	$result['error_code']=100;
    	returnApiSuccess($result,'发送短信完成');
    	
    }

	/**
	 * TODO 获取配送时间
     */
	public function get_distribution_time(){
		$order_id =I("post.order_id",'intval');
		$order_info = M("order_info")->field('best_time,best_time_start')->where('order_id = '.$order_id)->find();
		if($order_info['best_time']-$order_info['best_time_start']==37800){
			$today = 0;
		}else{
			$today = 1;
		}
		//查询送货时间
    	$Distribution_time = distributie_time_list($today);
    	returnApiSuccess($Distribution_time,'Distribution_time');
    }

	/**
	 *
	 *
	 *
	 * TODO 修改密码
     */
	public function edit_password(){
		$name=I('post.name','');
		$password_old = I('post.password_old','');
		$password_new = I('post.password_new','');

		//判断密码强度
		if (!preg_match("/^[a-za-z]{1}([a-za-z0-9]|[._]){5,16}$/",$password_new)){
			returnApiError("密码不符合规则\n密码需要首字母/6-16位/无特殊字符");
		}




		$admin_user=M('admin_user');
		$ec_salt=$admin_user->field('ec_salt')->where(array('user_name'=>$name))->find();
		if(!empty($ec_salt['ec_salt'])){
			$password=md5(md5($password_old).$ec_salt['ec_salt']);
			$new_password = md5(md5($password_new).$ec_salt['ec_salt']);
		}else{
			$password=md5($password_old);
			$new_password = md5($password_new);
		}

		$row=$admin_user->field('user_id,user_name')->where(array('user_name'=>$name,'password'=>$password))->find();
		//dump($admin_user->getlastsql());
		if($row){
			$edit = $admin_user->where(array('user_name'=>$name,'password'=>$password))->setField('password',$new_password);
			if($edit){
				$data=array(
					'log_time'=>gmtime(),
					'user_id'=>$row['user_id'],
					'log_info'=>$row['user_name']." [ ".$row['user_id']." ] 已成功修改密码",
					'ip_address'=>get_client_ip()
				);
				M('admin_log')->add($data);
				returnApiSuccess(null,"修改成功");
			}else{
				returnApiError("内部错误：修改密码失败");
			}
		}else{
			returnApiError("原密码/用户名不匹配");
		}
	}

	/**
	 * TODO 退单处理
     */
	public function return_order(){
		$user_id=I('post.user_id','intval');
		$order_id=I('post.order_id','intval');
		$remark=I('post.remark','');
		if(empty($remark)||is_numeric($remark)){
			returnApiError("请务必填写您退单的原因");
		}
		$wp=$this->check_warehouse_personnel($user_id);
		if(!$wp){
			returnApiError('非法用户或者该用户已被禁用');
		}

		$where_tow['shipping_id'] = 3;
		$where_tow['pay_status'] = array('IN','2,3');
		$where_tow['order_status'] = array('NEQ',2);
		$where['order_id'] = $order_id;
		$where['shipping_status'] = array("in","0,1,3");	//配货中，配送中

		$order_info = M("order_info")->where($where)->find();
		if($order_info){
			if($order_info['shipping_status'] == 1){
				//配送中【退单操作】
				$a=array(
					'order_id'=>$order_info['order_id'],
					'user_id'=>$user_id,
					'order_status'=>$order_info['order_status'],
					'shipping_status'=>5,	//配货完成
					'pay_status'=>$order_info['pay_status'],
					'action_note'=>$remark.'///由发货中退回到配送完成'
				);
				$this->record_diliveryman_log($a);//记录配送员操作日志
				$data['wp_userid']=0;
				$data['shipping_status']=5;
				$r = M('order_info')->where("order_id = ".$order_info['order_id'])->save($data);
				if($r){
					returnApiSuccess(null,"成功");
				}else{
					returnApiError("失败");
				}
			}else{
				//配货中【退单操作】
				if($order_info['sorting_id'] >0){
					$a=array(
						'order_id'=>$order_info['order_id'],
						'user_id'=>$user_id,
						'order_status'=>$order_info['order_status'],
						'shipping_status'=>0,	//未配货
						'pay_status'=>$order_info['pay_status'],
						'action_note'=>$remark.'///由配货中退回到未配货状态'
					);
					$this->record_diliveryman_log($a);//记录配送员操作日志
					$data['sorting_id']=0;
					$data['shipping_status']=0;
					$r = M('order_info')->where("order_id = ".$order_info['order_id'])->save($data);
					if($r){
						returnApiSuccess(null,"成功");
					}else{
						returnApiError("失败");
					}
				}
			}
		}else{
			returnApiError("无法进行此操作");
		}


	}
}